/*
 * I'm going to test the libraries ipseek and maketraf
 * using threads
 *
 */

#include <stdio.h>
#include <netinet/in.h>
#include <pthread.h>
#include <time.h>

struct __ipseek_param {
	char *dev;
	char *mac;
	struct in_addr *ipfound;
};

int _continue = 0;

/* Wrapper to create an ipseek thread */
void *t_ipseek_wrapper(void *parameters)
{
	struct __ipseek_param *ipseek_param = (struct __ipseek_param *) parameters;	
	return ip_seek(ipseek_param->mac, ipseek_param->dev, ipseek_param->ipfound);
}

void *t_maketraf_dhcp_wrapper(void *parameters)
{
	struct __ipseek_param *ipseek_param = (struct __ipseek_param *) parameters;	
	struct timespec requested_time;
	requested_time.tv_sec = 1;
	requested_time.tv_nsec = 0;

	while (_continue != 0){
		nanosleep(&requested_time,NULL);
		if (_continue != 0) send_dhcp_request(ipseek_param->dev);
	}
}

void *t_maketraf_icmp_wrapper(void *parameters)
{
	struct __ipseek_param *ipseek_param = (struct __ipseek_param *) parameters;	
	struct timespec requested_time;
	requested_time.tv_sec = 1;
	requested_time.tv_nsec = 0;
	
        while (_continue != 0) {
		nanosleep(&requested_time,NULL);
		if (_continue != 0) send_icmp_class_C(ipseek_param->dev);
	}
}


int main(int argc, char **argv)
{

	/* Be carefull with these variables */
	/* If main thread finishs before the threads, the next variables will be
	   deallocates and the threads will contain rubbish data */
	pthread_t t_ipseek;
	pthread_t t_maketraf_dhcp;
	pthread_t t_maketraf_icmp;

	if (argc != 3) {
		printf("I need the interface and mac\n");
		return -1;
	}

	char *mac=argv[2];
	char *dev=argv[1];
	struct in_addr ip;
	int result;

	struct __ipseek_param ipseek_param;
	ipseek_param.dev = dev;
	ipseek_param.mac = mac;
	ipseek_param.ipfound = &ip;

	//inet_ntoa("192.168.1.1",&ip);

	_continue = 1;

	/* Try to find the ip setting promiscuo mode in the network interface */
	result = pthread_create(&t_ipseek, NULL, t_ipseek_wrapper, &ipseek_param);
	printf("ip seek thread launched\n");

	pthread_create(&t_maketraf_dhcp, NULL, t_maketraf_dhcp_wrapper, &ipseek_param);
	printf("dhcp traffic thread launched\n");

	pthread_create(&t_maketraf_icmp, NULL, t_maketraf_icmp_wrapper, &ipseek_param);
	printf("icmp traffic thread launched\n");	
	
	printf("Waiting for ip seek thread\n");
	pthread_join(t_ipseek, NULL);
	
        _continue = 0; 

	/* At this point would be better to cancel nanosleep functions instead of waiting */
	printf("Waiting for dhcp traffic thread\n");
	pthread_join(t_maketraf_dhcp, NULL);
	printf("Waiting for icmp traffic thread\n");
	pthread_join(t_maketraf_icmp, NULL);

	printf("IP FOUND: %s\n",inet_ntoa(ip));

	return 0;

	/* Results :
	   The icmp traffic and dhcp traffic is sent before the network interface is listening 
	*/
	
}
